//
//  ZHHotController.swift
//  ZZLeSay
//
//  Created by 赵正华 on 16/7/26.
//  Copyright © 2016年 赵正华. All rights reserved.
//

import UIKit
import AFNetworking
import MJRefresh

class ZHHotController: UICollectionViewController {
   
    var dataArray = [ZHHotModel]() {
        didSet{
           self.collectionView?.reloadData()
        }
    }
    
    init(){
        
        //创建流水布局对象
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(172, 250)
        //设置垂直滚动
        layout.scrollDirection = .Vertical;
        // 设置cell之间间距
        layout.minimumInteritemSpacing = 0;
        // 设置行距
        layout.minimumLineSpacing = 10;
        
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
        
        super.init(collectionViewLayout: layout)
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.seNavUI()
       
        
        self.collectionView?.registerNib(UINib.init(nibName: "ZHHotCollectionCell", bundle: nil), forCellWithReuseIdentifier: "cellID")
        collectionView!.backgroundColor = UIColor.whiteColor()
        //下拉刷新
        self.collectionView?.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
             self.reloadNetworkData()
        })
        self.collectionView?.mj_header.beginRefreshing()

   }
     private func reloadNetworkData(){
        
        ZHNetworkTools.shareInstance.loadHotNetworkData { (result, error) in
            if error != nil{
              return
            }
            self.collectionView?.mj_header.endRefreshing()
            for dicts in result!{
                let dict = dicts["data"] as? [String : AnyObject]
                let model = ZHHotModel.init(dict: dict!)
                self.dataArray.append(model)
            }
        }
    }
    private func seNavUI(){
        navigationItem.rightBarButtonItem = UIBarButtonItem(searchTarget: self, seletor: #selector(self.clickSearchButton))
        title = "热门"
    }
    @objc func clickSearchButton(){
        navigationController?.pushViewController(ZHSeachViewController(), animated: true)
    }
}
extension ZHHotController{
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if self.dataArray.count == 0 {
            return 0
        }
        return self.dataArray.count;
    }
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cellID = "cellID"
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellID, forIndexPath: indexPath) as! ZHHotCollectionCell
        cell.hotModel = self.dataArray[indexPath.row];
        return cell
        
    }
}
